๋ฌธ์
๐ Logic
// ๋ชจ๋ 110 ๊ฐ์ ์นด์ดํธ
for(int i = 0; i < str.length(); i++) {
stack.push(str.charAt(i));
if (stack.size() < 3) continue;
char first = stack.pop();
if(first != '0') {
stack.push(first);
continue;
}
char second = stack.pop();
if(second != '1') {
stack.push(second);
stack.push(first);
continue;
}
char third = stack.pop();
if(third != '1') {
stack.push(third);
stack.push(second);
stack.push(first);
continue;
}
strCount++;
}
- ์คํ์ ์ฌ์ฉํด ์ฃผ์ด์ง ๋ฌธ์์ด์ ์๋ ๋ชจ๋ 110์ ๊ฐ์๋ฅผ ์นด์ดํธํ๋ค.
๐ CODE
์ฝ๋ ๋ณด๊ธฐ/์ ๊ธฐ๐ซ
import java.util.*;
class Solution {
public String[] solution(String[] s) {
int len = s.length;
String[] answer = new String[len];
for (int i = 0; i < len; i++)
answer[i] = findFirst(s[i]);
return answer;
}
private String findFirst(String s) {
String ooz = "110";
Stack<Character> stack = new Stack<>();
String str = s;
int strCount = 0;
// ๋ชจ๋ 110 ๊ฐ์ ์นด์ดํธ
for(int i = 0; i < str.length(); i++) {
stack.push(str.charAt(i));
if (stack.size() < 3) continue;
char first = stack.pop();
if(first != '0') {
stack.push(first);
continue;
}
char second = stack.pop();
if(second != '1') {
stack.push(second);
stack.push(first);
continue;
}
char third = stack.pop();
if(third != '1') {
stack.push(third);
stack.push(second);
stack.push(first);
continue;
}
strCount++;
}
StringBuilder sb = new StringBuilder();
int index = -1, size = stack.size() - 1;
// ์คํ ๊ฐ์ sb ๋งจ ์์ ์ถ๊ฐ
// 0์ ๋ง๋๋ฉด index ์ฆ๊ฐ
while(!stack.isEmpty()) {
char value = stack.pop();
sb.insert(0, value);
if(index == -1 && value == '0')
index = size;
size--;
}
// ๋จ์ strCount๋งํผ ์ถ๊ฐ
// index == -1์ด๋ผ๋ฉด, ๋จ์ ๋ฌธ์์ด์ 0์ด ์๋ค๋ ์๋ฏธ๋ก, ๋งจ ์์ 110์ ๋ถ์ฌ์ผ ํจ
// ๊ทธ๋ ์ง ์๋ค๋ฉด, index + 1๋ถํฐ 110์ ๋ถ์ฌ์ผ ํจ
int offset = index == -1 ? 0 : ++index;
while(strCount-- > 0)
sb.insert(offset, ooz);
return sb.toString();
}
}
โ๏ธ Review
-
์ฒ์ ์์ด๋์ด๋ 110 ์ ์ ๊ฑฐํ๊ณ , ๋จ์ ๋ฌธ์์ด์ ๋ชจ๋ ์ธ๋ฑ์ค์ 110์ ๋ถ์ฌ๋ณด๋ฉด์ ์ฌ์ ์ ๋น ๋ฅธ ๋ฌธ์์ด์ ์ฐพ์ผ๋ ค ํ๋ค.
- ์ด ์์ด๋์ด์์, 110์ด ์ฌ๋ฌ ๊ฐ ์์ ์ ์๋ค๋ ๊ฒ์ ๊ฐ๊ณผํ๋ค.
-
110์ด ์ฌ๋ฌ ๊ฐ ์กด์ฌํ๋ ๊ฒฝ์ฐ์, 0์ ๋ค์๋ง 110์ ๋ถ์ธ๋ค๋ ์กฐ๊ฑด ํ์ ๊ตฌํํ๋ค๊ฐ ์๊ฐ์ด๊ณผ๊ฐ ๋์, ์๋ง ๋ฌธ์์ด์ ๋ถ์ด๋ ์ฐ์ฐ๊ณผ 110์ ์ฐพ๋ ์ฐ์ฐ๋๋ฌธ์ธ ๊ฒ ๊ฐ์ ๋ค๋ฅธ ๋ฐฉ๋ฒ์ ์ฐพ์๋ณด๋ค๊ฐ ์คํ์ ํจ๊ป ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ ํํ๋ค.
- ๊ทผ๋ฐ ์ด ๋ฐฉ๋ฒ์ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ ๊ฒ ์ฐ๊ณ ์๊ฐ์ ๋ ์ฐ๋ ๋ฐฉ๋ฒ์ด๋ค .. ? (์คํ pop, push ์ฐ์ฐ ๋๋ฌธ์ธ ๊ฒ ๊ฐ๋ค.)
- ์๊ฐ์ด๊ณผ๊ฐ ๋ฐ์ํ๋ ์ฝ๋๋ฅผ ์ค์ด๊ธฐ ์ํด ๊ฐ ๋ฉ์๋์ ์๊ฐ๋ณต์ก๋๋ฅผ ์๊ฐํ๋ ์ต๊ด์ ๊ธธ๋ฌ์ผ๊ฒ ๋ค.